import datetime as dt
import backtrader as bt
import pandas as pd

class TQSta001(bt.Strategy):

    def log(self, txt, dt=None):
        # log记录函数
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))

    def __init__(self):
        # 默认数据，一般使用股票池当中，下标为0的股票，
        # 通常使用close收盘价，作为主要分析数据字段
        self.dataclose = self.datas[0].close
        self.order = None
        self.buyprice = None
        self.butcomm = None
        self.sma = bt.indicators.SimpleMovingAverage(
            self.datas[0], period = 15
        )

    def next(self):
        # next函数是最重要的trade交易（运算分析）函数， 
        # 调用log函数，输出BT回溯过程当中，工作节点数据包BAR，对应的close收盘价
        # self.log('Close收盘价, %.2f' % self.dataclose[0])

        if self.order:
            return
        
        if self.sma[0] > self.dataclose[0]:
            self.log("设置买入，单价为：%.2f" % self.dataclose[0])
            self.order = self.buy()
                    
        if self.sma[0] < self.dataclose[0]:
            self.log("设置卖出，单价为：%.2f" % self.dataclose[0])
            self.order = self.sell()
            # if len(self) >= (self.bar_executed + 5):
            #     

df = pd.read_csv('../hist_data/0246.csv', parse_dates=True, index_col=0)
feed = bt.feeds.PandasData(dataname=df, openinterest=None)

cerebro = bt.Cerebro()
cerebro.broker.setcash(100000.0)
cerebro.broker.startingcash
cerebro.adddata(feed)
cerebro.addstrategy(TQSta001)
cerebro.broker.setcommission(commission=0.001)
cerebro.addsizer(bt.sizers.FixedSize, stake=10)
cerebro.run()
dva19 = cerebro.broker.getvalue()
print("the final value is %.2f" % dva19)

cerebro.plot(style="candle")